package com.xingdata.jjxc.activity;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.xingdata.jjxc.BuildConfig;
import com.xingdata.jjxc.R;
import com.xingdata.jjxc.base.Base1Activity;
import com.xingdata.jjxc.base.BaseActivity;
import com.xingdata.jjxc.file_service.FileMD5Checker;
import com.xingdata.jjxc.file_service.UploadLogService;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.net.Socket;

/**
 * Created by dsit_dev04 on 2016/10/12.
 */
public class UpdateActivity extends Activity implements View.OnClickListener {
    private ImageView returnImageView;
    private Button btn_update;
    String  TAG = "UpdateActivity";
    private ProgressBar uploadbar;
    private TextView txt_loading;
    private TextView txt_version_name;
    private UploadLogService logService;
    private boolean start=true;

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            int length = msg.getData().getInt("size");
            uploadbar.setProgress(length);
            float num = (float)uploadbar.getProgress()/(float)uploadbar.getMax();
            int result = (int)(num * 100);
            txt_loading.setText(result+"%");
            if(uploadbar.getProgress()==uploadbar.getMax()){
                Toast.makeText(UpdateActivity.this, "设备进入OTA升级，请稍后重新连接设备热点!", Toast.LENGTH_LONG).show();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.activity_update);
        txt_version_name = (TextView)findViewById(R.id.version_name);

        uploadbar = (ProgressBar)findViewById(R.id.progressBar2);
        txt_loading = (TextView)findViewById(R.id.txt_loading_progress);
        uploadbar.setVisibility(View.GONE);
        txt_loading.setVisibility(View.GONE);

        btn_update = (Button)findViewById(R.id.btn_update);
        btn_update.setOnClickListener(this);
        
        logService = new UploadLogService(this);
//         StatusBarBackChange.setStatusBarBack(this);
        returnImageView = (ImageView)findViewById(R.id.check_update_return_button);
        returnImageView.setOnClickListener(this);
//        UdpRxThread.setDataListener(dataListener);
    }

    @Override
    public void onClick(View v){
        switch(v.getId()){
            case R.id.btn_update:
                if(!isLoading){
                    File otafile = new File("/sdcard/hud_ota.zip");
                    if(otafile.exists()){
                        Log.i(TAG,"===========> update data file exist");
                        uploadFile(otafile);
                        uploadbar.setVisibility(View.VISIBLE);
                        txt_loading.setVisibility(View.VISIBLE);
                        Toast.makeText(UpdateActivity.this, "正在开始升级，请耐心等待...", Toast.LENGTH_LONG).show();
                    }else{
                        Toast.makeText(UpdateActivity.this, "/sdcard/hud_ota.zip 升级文件不存在!", Toast.LENGTH_LONG).show();
                    }
                }else{
                    // // TODO: 2016/10/28 Stop loading
                }
                break;
            case R.id.check_update_return_button:
                finish();
            default:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            if(socket!=null)
                socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if(loadingThread!=null &&loadingThread.isAlive())
            loadingThread.stop();
    }

    void setVersionTextName(final String textName){
        handler.post(new Runnable() {
            @Override
            public void run() {
                txt_version_name.setText(textName);
            }
        });
    }

    boolean isLoading = false;
    Thread loadingThread;
    Socket socket;
    /**
     * 上传文件
     * @param uploadFile
     */
    private void uploadFile(final File uploadFile) {
        if(isLoading)
            return;

        uploadbar.setMax((int)uploadFile.length());
        loadingThread= new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Log.i(TAG,"start update loading...");

                    String souceid = logService.getBindId(uploadFile);
                    String head = "Content-Length="+ uploadFile.length() + ";filename="+ uploadFile.getName() + ";sourceid="+
                            (souceid==null? "" : souceid)
                            +";md5="+ FileMD5Checker.calculateSingleFileMD5sum(uploadFile)
                            +"\r\n";
                    Log.i(TAG,"--------> file info: "+head);
                    socket = new Socket("192.168.43.1",30005);
                    OutputStream outStream = socket.getOutputStream();
                    outStream.write(head.getBytes());

                    RandomAccessFile fileOutStream = new RandomAccessFile(uploadFile, "r");
                    byte[] buffer = new byte[8*1024];
                    int len = -1;
                    int length = 0;
                    while(start&&(len = fileOutStream.read(buffer)) != -1){
                        outStream.write(buffer, 0, len);
                        length += len;
                        Message msg = new Message();
                        msg.getData().putInt("size", length);
                        handler.sendMessage(msg);
                        isLoading = true;
                        if(BuildConfig.DEBUG)
                            Log.e(TAG,"--------> loading:"+ 100 * (float)length /uploadFile.length());
                    }
                    fileOutStream.close();
                    outStream.close();
                    socket.close();
                    socket = null;
                    if(length==uploadFile.length()) logService.delete(uploadFile);
                    isLoading = false;
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.e(TAG,"--------> upload error: "+e.getMessage());
                    isLoading =false;
                }
            }
        });loadingThread.start();

    }
}
